#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>

int get_temperature(float *temp);	//调用

int main(int argc, char *argv[])
{
	float		temp;
	int		rv;	//返回值
	
	rv = get_temperature(&temp);
	if( rv < 0 )
	{
		printf("get_temperature fialure, return value: %d", rv);
		return -1;
	}
	
	printf("temperature: %f\n",temp);
}


int get_temperature(float *temp)
{
	int		fd=-1;
	char   		buf[128];	//一般给2的次方
	char   		*ptr = NULL;
	DIR		*dirp = NULL;	//DIR结构体类似于FILE，是一个内部结构
	struct dirent	*direntp = NULL;	//dir结构体 
	char		w1_path[64]="/sys/bus/w1/devices/";
	char		chip_sn[32];
	int		found = 0;
	int		i = 0;

     	time_t 		now_time;	//定义时间变量

	dirp=opendir(w1_path);		//打开目录
	if( !dirp)
	{
		printf("open folder %s failure: %s\n", w1_path, strerror(errno));
		return -1;
	}


	while( (direntp=readdir(dirp)) != NULL)		//读路径
	{
		if( strstr(direntp->d_name, "28-") )	//在文件名中查找第一次出现字符串 28- 的位置，不包含终止符 '\0'
		{
			strncpy(chip_sn, direntp->d_name, sizeof(chip_sn));	//把这个名字复制到chip_sn中
			found = 1;
		}
	}
        closedir(dirp);


	if( !found )	//没找到 28- 开头文件的情况
	{
		printf("Can not find ds18b20 chipset\n");
		return -2;
	}

//	snprintf(ds18b20_path, sizeof(ds18b20_path), "%s/%s/w1_slave\n", w1_path, chip_sn);
//	printf("w1_path: %s\n", ds18b20_path);


	strncat(w1_path, chip_sn, sizeof(w1_path)-strlen(w1_path));
	strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));
//	printf("w1_path: %s\n",w1_path);


	fd=open(w1_path,O_RDONLY);
	if(fd < 0)
	{
		printf("open file failure: %s\n",strerror(errno));
        	return -3;
	}     


     	memset(buf, 0, sizeof(buf));	//字符串以\0结尾，\0是0，初始化

     	if( read(fd, buf, sizeof(buf)) < 0 )
	{
     		printf("read data from fd=%d failure: %s\n", fd ,strerror(errno));
		return -4;
	}
//     	printf("buf: %s\n", buf);	//文件内容在buf里，打印buf

     	ptr=strstr(buf, "t=");		//寻找文件中 t= 的内容
     	if(!ptr)
     	{
        	printf("Can not find t= string\n");
        	return -5;
     	}

     	ptr +=2;	//去掉“t=”，只留下温度值
        while(i<11)
	{
		time(&now_time);	//获取时间
	 	printf("Time: %s",ctime (&now_time) );

		*temp = atof(ptr)/1000;		//ASCII转float
     		printf("temprature: %f\n\n", *temp);
		sleep(5);	//每隔5s打印一次

		i++;
	}

     	close(fd);

	return 0;

}
